<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <div class="table-operator">
        <a-button
          @click="$refs.modalEdit.add()"
          type="primary"
          icon="plus"
          v-wx-role="100801"
          >添加</a-button
        >
      </div>
      <s-table
        ref="table"
        rowKey="id"
        size="middle"
        :scroll="{ x: 500 }"
        :columns="columns"
        :alert="options.alert"
        :data="loadData"
      >
        <template slot="status" slot-scope="text, record">
          {{ text == '0' ? '禁用' : '启用' }}
        </template>
        <template slot="condition" slot-scope="text, record">
          <div
            style="margin: 5px 0px"
            v-for="item in getFilterSelectName(text)"
          >
            {{ item }}
          </div>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-wx-role="100802">
            <a-icon type="edit" />编辑</a
          >
          <a-divider type="vertical" />

          <a-popconfirm
            title="确定删除吗?"
            @confirm="() => handleDelete(record.id)"
            v-wx-role="100803"
          >
            <a>删除</a>
          </a-popconfirm>
        </template>
      </s-table>

      <dev-archive-filter-group-edit
        ref="modalEdit"
        @ok="modalEditOk"
      ></dev-archive-filter-group-edit>
      <dev-archive-filter-group-view
        ref="modalView"
      ></dev-archive-filter-group-view>
    </div>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { deleteAction, postAction, getAction } from '@/api/manage'
import { mixin } from '@/utils/mixin'
import DevArchiveFilterGroupEdit from './DevArchiveFilterGroupEdit'
import DevArchiveFilterGroupView from './DevArchiveFilterGroupView'
import DevCampusTree from '../../../../components/CampusTree/DevCampusTree.vue'

export default {
  name: 'DevArchiveFilterGroupList',
  mixins: [mixin],
  components: {
    STable,
    Ellipsis,
    DevArchiveFilterGroupEdit,
    DevArchiveFilterGroupView,
    DevCampusTree,
  },
  data() {
    return {
      selectList: {
        commonName: {
          name: '通用名',
          type: 'selectUrl',
          dictType: '',
        },
        cfda: {
          name: 'CFDA',
          type: 'select',
          dictType: 'CFDA',
        },
        activeState: {
          name: '使用状态',
          type: 'select',
          dictType: 'activeState',
        },
        assetStatus: {
          name: '资产状态',
          type: 'select',
          dictType: 'assetStatus',
        },
        repairState: {
          name: '保修状态',
          type: 'select',
          dictType: 'repair_state',
        },
        assetCode: {
          name: '资产编码',
          type: 'select',
          dictType: 'assetCode',
        },
        fixedAssets: {
          name: '固定资产',
          type: 'select',
          dictType: 'fixedAssets',
        },
        period: {
          name: '有效期',
          type: 'select',
          dictType: 'period',
        },
        deviceType: {
          name: '类型',
          type: 'tree',
        },
        professionalClassificationId: {
          name: '专业分类',
          type: 'tree',
        },
        currentLocation: {
          name: '当前位置',
          type: 'cascader',
        },
        departmentId: {
          name: '所属科室',
          type: 'tree',
        },
        usingDepartmentId: {
          name: '使用科室',
          type: 'tree',
        },
        supplierName: {
          name: '供应商',
          type: 'input',
        },
        importedDomestic: {
          name: '进口/国产',
          type: 'select',
          dictType: 'importedDomestic',
        },
        differentCountrie: {
          name: '国别',
          type: 'select',
          dictType: 'differentCountrie',
        },
        manufacturerName: {
          name: '生产厂商',
          type: 'input',
        },
        assetValueMin: {
          name: '资产价值',
          type: 'number',
        },
        assetValueMax: {
          name: '资产价值',
          type: 'number',
        },
        purchaseDate: {
          name: '采购日期',
          type: 'date',
        },
        expiringDate: {
          name: '失效日期',
          type: 'date',
        },
        acceptanceDate: {
          name: '验收日期',
          type: 'date',
        },
        entryDate: {
          name: '录入日期',
          type: 'date',
        },
        inputMethod: {
          name: '录入方式',
          type: 'select',
          dictType: 'inputMethod',
        },
        enterSource: {
          name: '录入来源',
          type: 'select',
          dictType: 'enterSource',
        },
        administrativeDept: {
          name: '管理部门',
          type: 'select',
          dictType: 'administrativeDept',
        },
        deviceClassificationId: {
          name: '器械分类',
          type: 'tree',
        },
        mandatoryInspectionCatalogId: {
          name: '强检目录',
          type: 'tree',
        },
        politicalProcurementCatalogueId: {
          name: '政采目录',
          type: 'tree',
        },
        commonMilitaryNameId: {
          name: '部队通用名',
          type: 'tree',
        },
        fixedClassificationId: {
          name: '固资分类',
          type: 'tree',
        },
        fixedAssetClassificationCodeId: {
          name: '高等学校固定资产分类',
          type: 'tree',
        },
      },
      visible: false,
      // 查询条件
      queryParam: {
        title: '',
      },
      // 表头
      // 如果需要字典，那么需要在columns列中加入 customRender: (text) => this.$sysDictFilter(text, 'xxxx')xxxx 为dataIndex
      columns: [
        {
          title: '筛选组名称',
          dataIndex: 'name',
        },
        {
          title: '筛选组条件',
          dataIndex: 'condition',
          scopedSlots: { customRender: 'condition' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '排序',
          dataIndex: 'sortOrder',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        console.log('loadData.parameter', parameter)
        return postAction(
          this.url.list,
          Object.assign(parameter, this.queryParam)
        ).then((res) => {
          return res.result
        })
      },
      commonNameList: [],
      listTree: [],
      selectedRowKeys: [],
      options: {
        alert: {
          clear: () => {
            this.selectedRowKeys = []
          },
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
          type: 'checkbox',
        },
      },
      url: {
        list: '/system/devArchiveFilterGroup/list',
        delete: '/system/devArchiveFilterGroup/delete',
        getprofessionalClassificationIdTree:
          '/system/devProfessionalClassification/tree',
        getClassificationTree: '/system/devArchiveDeviceClassification/tree',
        getMandatoryInspectionCatalogTree:
          '/system/devArchiveMandatoryInspectionCatalog/tree',
        getPoliticalProcurementCatalogueTree:
          '/system/devArchivePoliticalProcurementCatalogue/tree',
        getCommonMilitaryNameTree: '/system/devArchiveCommonMilitaryName/tree',
        getFixedClassificationTree:
          '/system/devArchiveFixedClassification/tree',
        getFixedAssetClassificationCodeTree:
          '/system/devArchiveFixedAssetClassificationCode/tree',
        getCampusBuildingFloorRoomTree:
          '/system/devCampusBuildingFloorRoom/listTree',
        getDevArchiveCommonNameList: '/system/devArchiveCommonName/getList',
      },
    }
  },
  computed: {},
  created() {
    this.getListTree()
    //通用名
    this.getCommonNameList()
  },
  methods: {
    //通用名
    getCommonNameList() {
      getAction(this.url.getDevArchiveCommonNameList).then((res) => {
        this.commonNameList = res.result.data
      })
    },
    getFilterSelectName(text) {
      var selectContent = []

      var obj = JSON.parse(text)
      for (const key in obj) {
        console.log('key>>', key) // "assetStatus"
        // 如果你只需要第一个key，可以在这里break
        // 判断该key对应的值是否为空
        if (obj[key]) {
          console.log(`${key}的值不为空`)
          var object = this.selectList[key]

          var value = ''
          if (object.type == 'number') {
            if (key == 'assetValueMin' || key == 'assetValueMax') {
              var assetValueMin = obj['assetValueMin']
              var assetValueMax = obj['assetValueMax']
              //var name = object.name + '：' + assetValueMin + "~" + assetValueMax;
              value = assetValueMin + '~' + assetValueMax
              // selectContent.push(name);
              // return selectContent;
            }
          }
          if (object.type == 'input' || object.type == 'date') {
            value = obj[key]
          }
          if (object.type == 'select') {
            var dictList = this.$sysDictOptions(object.dictType)

            value = dictList[`wx${obj[key]}`].v
          }
          if (object.type == 'selectUrl') {
            value = this.getCommonName(obj[key])
            console.log('obj.commonName>>', value)
          }
          if (object.type == 'tree') {
            var treeList = obj[key]

            var treeValue = ''
            treeList.forEach((tree) => {
              treeValue = treeValue + tree.label + ','
            })
            value = treeValue.substring(0, treeValue.length - 1)
          }

          if (object.type == 'cascader') {
            var roomList = obj[key]
            var roomValue = ''
            roomList.forEach((id) => {
              var aa = this.getFindNodeByKey(this.listTree, id)
              roomValue = roomValue + aa.label + ','
            })
            value = roomValue.substring(0, roomValue.length - 1)
          }

          if (value) {
            var name = object.name + '：' + value
            selectContent.push(name)
          }
        }
      }
      console.log('selectContent2:', selectContent)
      return [...new Set(selectContent)]
    },

    getCommonName(commNameId) {
      var obj = this.commonNameList.filter((aa) => aa.id + '' == commNameId)[0]
      if (obj) {
        return obj.commonName
      }
    },
    getListTree() {
      getAction(this.url.getCampusBuildingFloorRoomTree).then((res) => {
        this.listTree = res.result.data
      })
    },
    getFindNodeByKey(tree, key) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].value === key) {
          return tree[i] // 找到匹配项，返回该节点
        } else if (tree[i].children) {
          // 递归搜索子节点
          const found = this.getFindNodeByKey(tree[i].children, key)
          if (found) return found // 如果在子节点中找到，返回该节点
        }
      }
      return null // 未找到匹配项
    },
    // 删除
    handleDelete(record) {
      if (!record) {
        // 如果没有传入，那么批量删除
        record = this.selectedRowKeys.join(',')
      }
      deleteAction(this.url.delete, { ids: record }).then((resp) => {
        this.$message.success('删除成功!')
        this.$refs.table.refresh(true)
      })
    },
    // 用户编辑
    handleEdit(record) {
      this.$refs.modalEdit.edit(record)
    },
    searchQuery() {
      this.$refs.table.refresh(true)
    },
    // 保存刷新
    modalEditOk() {
      this.$refs.table.refresh()
    },
    // 查看
    handelView(record) {
      this.$refs.modalView.show(record)
    },
    //开启选择
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
  },
  watch: {},
}
</script>
<style scoped></style>
